# -*- coding: utf-8 -*-
import requests
import os
import sys
import time
import json
import xxx_sort
from requests import Response

type=sys.getfilesystemencoding()

requests.packages.urllib3.disable_warnings()

# allfile = []
wvsserver = "https://127.0.0.1:3443/"
apikey = "1986ad8c0a5b3df4d7028d5f3c06e936c450e5d1c3fc448eb8696cc9bb310db66"
wvs_headers = {"X-Auth": apikey, "content-type": "application/json"}

allfilelist = os.listdir('./')
allcookfile = []

# 定义登录请求url和账号相关常量
headers = {"X-Requested-With": "XMLHttpRequest"}
c_url = "https://basepassport.xxx.com/account/v1/login.json"
c_payload = {'callback': 'jsonp372075', 'businessId': '1100100017', 'login': '15190990037',
             'pwd': '44f7a4610c767a6125552dcdd77ff9e6',
             'captchaData': 'ttvX4X1fsJZ6mEpJK6crnP8sWJiYIWlFrUY7f8BNcqeGJoFWGu',
             'captchaSign': 'XTmi8Jm5vvYCCUqgXyXBB27IIWdcWY4E3nI1k5lOC5xRbI5hFGpisPEUPLLMe4RudynLEgTgUoeW0RCNqB48ZK74uDzihAUkYvs'}
mc_url = "https://basepassport.xxx.com/account/v1/loginbytel.json?callback=jsonp45846&businessId=1100100012&tel=15190990037&smsCode=900702&url=&mscid=&_bi_role=c&_bi_source=4"
mc_payload = {}

xy_url = "https://basepassport.xxx.com/account/v1/login.json"
xy_payload = {'callback': 'jsonp542341', 'businessId': '1100100017', 'login': 'lt77@cs.com',
              'pwd': '3b97444f97e36cef4a6221be667db27d',
              'captchaData': 'ttvX4X1fsJZ6mEpJK6crnP8sWJiYIWlFrUY7f8BNcqeGJoFWGu',
              'captchaSign': 'XTmi8Jm5vvYCCUqgXyXBB27IIWdcWY4E3nI1k5lOC5xRbI5hFGpisPEUPLLMe4RudynLEgTgUoeW0RCNqB48ZK74uDzihAUkYvs'}

h_url = "https://basepassport.xxx.com/account/v1/login.json"
h_payload = {'callback': 'jsonp542341', 'businessId': '1100100017', 'login': '18899991100',
             'pwd': '86b73c616014916f1525f18be8f6efac',
             'captchaData': 'ttvX4X1fsJZ6mEpJK6crnP8sWJiYIWlFrUY7f8BNcqeGJoFWGu',
             'captchaSign': 'XTmi8Jm5vvYCCUqgXyXBB27IIWdcWY4E3nI1k5lOC5xRbI5hFGpisPEUPLLMe4RudynLEgTgUoeW0RCNqB48ZK74uDzihAUkYvs'}
b_url = "https://passport.xxx.com/account/organization/v1/loginbytel.json"
b_payload = {'callback': 'jQuery17107681120640305703_1591771560569',
             'tel': '12999991133',
             'smsCode': '900702'}

lbb_url = "https://basepassport.lebanban.com/account/v1/loginbytel.json?callback=jsonp1&businessId=1100600002&tel=18899990000&smsCode=900702"
lbb_payload = {}

hpo_url = "http://visa.xxx.cn/auth/login.json"
hpo_data = {"loginName": "system", "password": "CB515B0C155BFCDEBDB96C4E0CB260BE"}
hpo_portalurl = 'http://portal.xxx.cn/loginbytoken'

clt_url = "https://basepassport-comp.xxx.com/account/v1/login.json"
clt_payload = {'callback': 'jsonp557671', 'businessId': '1100501006',
               'login': 'beijingqingtian',
               'pwd': 'e0a8aa81eb1762d529783cf587f6f422',
               'captchaData': 'ttvX4X1fsJZ6mEpJK6crnP8sWJiYIWlFrUY7f8BNcqeGJoFWGu',
               'captchaSign': 'XTmi8Jm5vvYCCUqgXyXBB27IIWdcWY4E3nI1k5lOC5xRbI5hFGpisPEUPLLMe4RudynLEgTgUoeW0RCNqB48ZK74uDzihAUkYvs'}

cdcb_url = "https://basepassport-vasemployee.xxx.com/account/v1/login.json"
cdcb_payload = {'callback': 'jsonp271242', 'businessId': '1100800001',
                'login': '18600209436',
                'pwd': 'e0a8aa81eb1762d529783cf587f6f422',
                'captchaData': 'ttvX4X1fsJZ6mEpJK6crnP8sWJiYIWlFrUY7f8BNcqeGJoFWGu',
                'captchaSign': 'XTmi8Jm5vvYCCUqgXyXBB27IIWdcWY4E3nI1k5lOC5xRbI5hFGpisPEUPLLMe4RudynLEgTgUoeW0RCNqB48ZK74uDzihAUkYvs'}

mcdcc_url = "https://basepassport-vasemployee.xxx.com/account/v1/loginbytel.json"
mcdcc_payload = {'callback': 'jsonp832373', 'businessId': '1100800002',
                'login': '17600110135',
                'smsCode': '900702'}

dm_url = "https://basepassport.xxx.com/account/v1/loginbytel.json"
dm_payload = {'callback': 'jsonp2', 'businessId': '1100400002',
              'tel': '18600209436',
              'smsCode': '900702'}





# print(allcookfile)

def addtarget(url):
    # 添加任务，返回任务id
    data = {"address": url, "description": url, "criticality": "10"}
    try:
        response = requests.post(wvsserver + "/api/v1/targets", data=json.dumps(data), headers=wvs_headers, verify=False)
        #print(response.content)
        result = json.loads(response.content)
        # print('add_task.....')
        #print('target_id is ' + result['target_id'])
        return result['target_id']
    except Exception as e:
        print(str(e))
        return


def setconfig(target_id, target_url, target_cookie):
    url = wvsserver + "api/v1/targets/" + target_id + "/configuration"
    data = {"limit_crawler_scope": True, "case_sensitive": "yes", "excluded_paths": [],
            "user_agent": "awvscan"}
    data2 = '{"issue_tracker_id":"","technologies":[],"custom_headers":["X-Requested-With:XMLHttpRequest"],"custom_cookies":[{"url":"' + target_url + '","cookie":"' + target_cookie + '"}],"debug":false,"excluded_hours_id":""}'
    #print(data2)
    print(target_url + '  已经加入到扫描队列\n'.decode('utf-8').encode(type))
    try:
        response = requests.patch(url, data=json.dumps(data), headers=wvs_headers, verify=False)
        response2 = requests.patch(url, data=data2, headers=wvs_headers, verify=False)
        # print(response.status_code)
        # print(response2.status_code)
    except Exception as e:
        print(str(e))


# 创建扫描
def startscan(target_id,url):
    # 创建扫描,返回扫描id
    data = {"target_id": target_id, "profile_id": "11111111-1111-1111-1111-111111111111",
            "schedule": {"disable": False, "start_date": None, "time_sensitive": False}}
    # print data
    if url.strip() != '':
        print(url+ '   start scan')
    try:
        response = requests.post(wvsserver + "/api/v1/scans", data=json.dumps(data), headers=wvs_headers, verify=False)
        result = response.headers
        # print('start_scan....')
        # print(response.status_code)
        scan_id = result['Location'].split('/')[4]
        return scan_id
    except Exception as e:
        print(str(e))
        return


def cookiejar2str(cookiejar):
    cookiedict = cookiejar.get_dict()
    result = ''
    for key in cookiedict:
        if cookiedict[key] == '\"\"':
            cookiedict[key] = '\\\"\\\"'
        tmp = key + "=" + cookiedict[key] + "; "
        result += tmp
    return result[:-2]



# 设置扫描任务
def setscantarget(cookie, filename):
    filename = "./" + filename
    #print(filename)
    file = open(filename)
    for line in file:
        target_id = str(addtarget(line.strip('\n')))
        setconfig(target_id, line.strip('\n'), cookie)
        #startscan(target_id,'')
        time.sleep(2)
    file.close()


# 返回cookie值
def cookiejar2str(cookiejar):
    cookiedict = cookiejar.get_dict()
    result = ''
    for key in cookiedict:
        if cookiedict[key] == '\"\"':
            cookiedict[key] = '\\\"\\\"'
        tmp = key + "=" + cookiedict[key] + "; "
        result += tmp
    return result[:-2]


# 获取非hpo登录接口cookie值
def get_nohpocookie(url, payload):
    #print(url,payload)
    try:
        #print(url)
        response = requests.get(url=url, params=payload, headers=headers)
        #print(response.cookies)
        cookies = response.cookies
        #print(cookies)
        return  cookies
    except Exception as e:
        return


# 获取各业务端cookie值函数
def funcookie(domaincookie):
    if domaincookie == "hpo":
        url = hpo_url
        try:
            response = requests.post(url=url, data=hpo_data, headers=headers)
            text = json.loads(response.content)
            dictonekey = text['data']
            portaltoken = dictonekey['token']
            payload = {'token': portaltoken}
            try:
                r = requests.get(hpo_portalurl, params=payload, allow_redirects=False)
                cookies = r.cookies
                return cookies
            except Exception as e:
                print(str(e))
                return
        except Exception as e:
            print(str(e))
            return
    elif domaincookie == 'c':
        url = c_url
        payload = c_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'b':
        url = b_url
        payload = b_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'mc':
        url = mc_url
        payload = mc_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'xy':
        url = xy_url
        payload = xy_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'h':
        url = h_url
        payload = h_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'lbb':
        url = lbb_url
        payload = lbb_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'clt':
        url = clt_url
        payload = clt_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'xxx':
        url = dm_url
        payload = dm_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'mcdcc':
        url = mcdcc_url
        payload = mcdcc_payload
        cookies = get_nohpocookie(url, payload)
        return cookies
    elif domaincookie == 'cdcb':
        url = cdcb_url
        payload = cdcb_payload
        cookies = get_nohpocookie(url, payload)
        return cookies


# 获取扫描对象(当前目录下txt文件内域名列表)
def getfilecookie():
    for i in allcookfile:
        filenamepre = i.split(".")[0]
        # print(filenamepre)
        if filenamepre == "nocookie":
            nocookie = "wvsscan"
            print(filenamepre)
            setscantarget(nocookie, i)
        else:
            print(filenamepre)
            domaincookies = funcookie((filenamepre))
            #print(domaincookies)
            #print(type(domaincookies))
            if domaincookies is None:
                print("当前域名登录错误,请检查  ".decode('utf-8').encode(type)+filenamepre+ "   登录配置信息".decode('utf-8').encode(type) )
                continue
            else:
                filenameprecookie = cookiejar2str(domaincookies)
                #print(filenameprecookie)
                setscantarget(filenameprecookie, i)

#获取提交任务信息列表
def gettargetlist():
    try:
        response = requests.get(wvsserver+'/api/v1/targets',headers=wvs_headers, verify=False)
        result = json.loads(response.content)
        #print(result)
        pagination = result['pagination']
        next_cursor = pagination['next_cursor']
        targets = result['targets']
        while next_cursor:
            response = requests.get(wvsserver + '/api/v1/targets?c='+str(next_cursor), headers=wvs_headers, verify=False)
            result = json.loads(response.content)
            pagination = result['pagination']
            next_cursor = pagination['next_cursor']
            targets.extend(result['targets'])
        if len(targets) == 0:
            print('现在无任务，请先建立扫描任务')
        else:
            for i in targets:
                #print(i['address'])
                if i['last_scan_session_status'] == 'completed' or i['last_scan_session_status'] == 'deleted'  or i['last_scan_session_status']  is None:
                    startscan(i['target_id'],i['address'])
                    time.sleep(30)
            #targetlist.append(i['target_id'])
    except Exception as e:
        return str(e)


if __name__ == "__main__":
    for i in allfilelist:
        if i.endswith(".txt"):
            allcookfile.append(i)
    getfilecookie()
    while True:
        gettargetlist()




